package antonst.dcl;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashSet;

class DynamicClassLoader extends ClassLoader {
	
	private final HashSet<String> dynamicClassNameSet = new HashSet<>();
	
	public DynamicClassLoader(ClassLoader parent){
		super(parent);
	}
	
	public void addDynamicClassName(String className){
		dynamicClassNameSet.add(className);
	}
	
	@Override
	public Class<?> loadClass(String name) throws ClassNotFoundException {
		if (!dynamicClassNameSet.contains(name))
			return super.loadClass(name);
		String classPath = name.replace('.', '/') + ".class";
		InputStream input = super.getResourceAsStream(classPath);
		ByteArrayOutputStream buffer = new ByteArrayOutputStream();
		int data;
		try {
			data = input.read();
			while(data != -1){
				buffer.write(data);
				data = input.read();
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				input.close();
			} catch (IOException e) { /* Nothing to do with it. */ }
		}
		byte[] classData = buffer.toByteArray();
		Class<?> clazz = defineClass(name,
				classData, 0, classData.length);
		return clazz;
	}
	
	
}
